<template>
  <div>
    <el-row class="nav">
      <i class="el-icon-arrow-left" @click="goBack"></i>
      <span class="font-weight">{{
        $store.state.newNoticeId ? "编辑通知模板" : "新建通知模板"
      }}</span>
    </el-row>
    <el-divider style="margin-bottom: 10px"></el-divider>
    <el-form
      ref="ruleForm"
      :model="form"
      :label-width="formLabel"
      :rules="ruleForm"
      style="width: 70%; margin: 0 auto"
    >
      <el-form-item label="模板名称：" prop="name">
        <el-input v-model="form.name" maxlength="20" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="描述：">
        <el-input v-model="form.discription"></el-input>
      </el-form-item>
      <el-form-item label="模板类型：" prop="type">
        <el-select
          v-model="form.type"
          @change="changeType"
          clearable
          placeholder="请选择模板类型"
          value=""
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.tenantId"
            :label="item.dictName"
            :value="item.dictCode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="模板内容："
        prop="msgContent"
      >
        <!-- 富文本 -->
        <quill-editor
          v-if="form.type === 'email'"
          ref="text"
          v-model="form.msgContent"
          style="min-height: 100px"
          :options="editorOption"
        />
        <!-- 纯文本 -->
         <el-input
          v-if="form.type !== 'email'"
          type="textarea"
          :rows="4"
          placeholder="请输入模板内容"
          v-model="form.msgContent"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="标题：" v-if="form.type==='email'" prop="msgTitle">
        <el-input
          placeholder="请输入标题"
          v-model="form.msgTitle"
          clearable>
        </el-input>
      </el-form-item>
      <el-form-item label="附件：" v-if="form.type === 'email'">
        <el-upload
          class="upload-demo"
          ref="upload"
          action="#"
          :http-request="uploadOk"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :file-list="form.fileList"
          :auto-upload="true"
        >
          <el-button slot="trigger" size="small" type="primary"
            >选取文件</el-button
          >
        </el-upload>
      </el-form-item>
     <el-form-item label="模板字段：">
        <el-tag
          class="custor"
          style="margin-left: 10px"
          v-for="item in tagList"
          :key="item.id"
          :data-clipboard-text="item.isSys !== 'Y' ? '{customField.'+item.dictCode+'}':'{'+item.dictCode+'}'"
          ><i class="el-icon-document-copy"  @click="selectTag(item)" alt="复制"></i>{{ item.dictName }}</el-tag>
      </el-form-item>
      <el-form-item label="是否跳转详情：" v-if="form.type === 'sys_msg'">
        <el-radio v-model="form.isGoDetails" label="Y">是</el-radio>
        <el-radio v-model="form.isGoDetails" label="N">否</el-radio>
      </el-form-item>
      <el-form-item style="text-align: right">
        <el-button
          type="button"
          class="el-button el-button--primary el-button--medium h30Btn"
          @click="submitForm('ruleForm')"
          >完成</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Clipboard from 'clipboard'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import {
  getNoticeTemp,
  newAddMsgTemp,
  getUploadFile,
  getInsertNotice,
  getInsertNoticeById
} from '@/api/setNotice'
import { getDictDetailListByPcode } from "@/api/setNotice.js"
export default {
  data () {
    var character = (rule, value, callback) => {
      var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？% ]")
      if (pattern.test(value)) {
        return callback(new Error('模板名称不能包含特殊字符'));
      } else {
        callback()
      }
    }
    return {
      tagList: [],
      formLabel: '130px',
      form: {
        name: '',
        discription: '',
        type: '',
        msgContent: '',
        msgTitle:'',
        isGoDetails: 'N',
        attachmentAddress: [],
        // fileList: [{ name: 'tstqe.458.txt', url: 'https://myrtc.egoonet.com/filesrv/get?filename=/00/13/test.xlsx' }],
        fileList: []
      },
      ruleForm: {
        name: [
          { required: true, message: '请输入模板名称', trigger: ['blur', 'submit'] },
          { validator: character, trigger: ['blur', 'submit'] }
        ],
        type: [
          { required: true, message: '请选择模板类型', trigger: ['blur', 'submit'] },
        ],
        msgContent: [
          { required: true, message: '请输入模板内容', trigger: ['blur','submit'] },
        ],
        msgTitle:[
          { required: true, message: '请输入标题', trigger: ['blur','submit'] },
        ]
      },
      typeOptions: []
    }
  },
  components: {
    quillEditor
  },
  mounted () {
    this.getNoticeTemp();
    const id = this.$store.state.newNoticeId
    if (id) {
      this.getTemplateById(id)
    }
    this.getDictDetailListByPcodeList()
  },
  methods: {
    selectTag (item) {
      let _this = this
      var clipboard = new Clipboard('.custor');
      clipboard.on('success', function(e) {
          _this.$message.success(item.dictName + "复制成功");
          // 销毁复制的元素,释放内存，防止多次弹出提示
         clipboard.destroy();
      });
      clipboard.on('error', function(e) {
          console.log(e);
          clipboard.destroy();
      }); 
    },
    getDictDetailListByPcodeList () {
      getDictDetailListByPcode('msg_template_param').then((res) => {
        if (res.data.retCode === 200) {
          this.tagList = res.data.data
        }
      })
    },
    // 获取详情
    getTemplateById (id) {
      getInsertNoticeById(id).then(res => {
        let data = res.data
        if (res.data.retCode === 200) {
          this.form.name = data.data.name
          this.form.discription = data.data.discription
          this.form.type = data.data.templateType
          this.form.msgContent = data.data.content
          this.form.isGoDetails = data.data.linkToWorkOrder
          if (this.form.type === 'email') {
            this.form.fileList = data.data.attachmentAddress.length > 0 ? data.data.attachmentAddress : []
            this.form.msgTitle = data.data.title || ''
          }
        }
      })
    },
    // 更改模板类型
    changeType () {
      this.form.msgContent = ''
      this.form.msgTitle = ''
      this.form.attachmentAddress = [],
      // fileList:[{name:'tstqe.458.txt',url:'https://myrtc.egoonet.com/filesrv/get?filename=/00/13/test.xlsx'}]
      this.form.fileList = []
    },
    // 文件上传
    uploadOk (val) {
      const formData = new FormData()
      formData.append('file', val.file);
      let tenantId = sessionStorage.getItem('tenantId') || 'default'
      if (val.file) {
        getUploadFile(formData, tenantId).then(res => { // 异步请求
          if (res.data.url) {
            this.$message.success("上传成功");
            this.fileList = [];
            this.form.fileList.push({
              name: val.file.name,
              url: res.url
            })
          } else {
            this.$message.error(res.error || '上传失败')
          }
        }).catch((err) => { })
      } else {
        this.$message({
          type: 'error',
          message: '请选择文件！'
        })
      }
    },
    handleRemove (file, fileList) {
      this.form.fileList.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.form.fileList.splice(index, 1)
        }
      })
    },
    handlePreview (file) {
      let fileUrl = this.form.fileList.filter((item) => {
        if (item.name === file.name) {
          return item.url;
        }
      })
      const elink = document.createElement("a");
      elink.download = file.name;
      elink.style.display = "none";
      elink.target = "_blank"
      elink.href = fileUrl;
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href);
      document.body.removeChild(elink);
    },
    // 获取模板类型
    getNoticeTemp () {
      getNoticeTemp().then(res => {
        if (res.data.retCode === 200) {
          this.typeOptions = res.data.data
          this.$message({ message: res.data.msg, type: 'success' })
        } else {
          this.$message({ message: res.data.msg, type: 'error' })
        }
      })

    },
    submitForm (formName) {
      let createParams = {
        name: this.form.name,
        templateType: this.form.type,
        discription: this.form.discription,
        content: this.form.msgContent,
        attachmentAddress: this.form.fileList.length > 0 ? this.form.fileList : [],
        linkToWorkOrder: this.form.isGoDetails,
        title: this.form.msgTitle
      }
      let updateParams = {
        name: this.form.name,
        id: this.$store.state.newNoticeId,
        templateType: this.form.type,
        discription: this.form.discription,
        content: this.form.msgContent,
        linkToWorkOrder: this.form.isGoDetails,
        attachmentAddress: this.form.fileList.length > 0 ? this.form.fileList : [],
        title: this.form.msgTitle
      }
      const id = this.$store.state.newNoticeId
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("submit")
          if (!id) {
            this.create(createParams)
          } else {
            this.update(updateParams)
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 新建
    create (params) {
      newAddMsgTemp(params).then(res => {
        if (res.data.retCode === 200) {
          this.$message({ message: res.data.msg, type: 'success' })
          this.$router.push('/setNotice')
        } else {
          this.$message({ message: res.data.msg, type: 'error' })
        }
      })
    },
    // 编辑
    update (params) {
      getInsertNotice(params).then(res => {
        if (res.data.retCode === 200) {
          this.$message({ message: res.data.msg, type: 'success' })
          this.$router.push('/setNotice')
        } else {
          this.$message({ message: res.data.msg, type: 'error' })
        }
      })
    },
    goBack () {
      this.$router.push('/setNotice')
    }
  }
}
</script>
<style scoped>
.title-txt {
  font-size: 12px;
  font-weight: bold;
  line-height: 25px;
}
.el-icon-document-copy {
  cursor: pointer;
  padding-right: 5px;
}
</style>
